package com.junjie.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.junjie.entity.Order;
import com.junjie.util.ConfigUtil;
import com.junjie.util.DBUtil;

public class OrderDaoImpl {
	/**
	 * 更新信息
	 */
	public int update(String sql, Object[] parameter) throws Exception {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		int id = 0;
	try {
		conn = DBUtil.getConnection();
		pstmt = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
		if(parameter != null && parameter.length>0){
			for (int i = 1; i <= parameter.length; i++) {
				pstmt.setObject(i, parameter[i-1]);
			}
		}
		int result = pstmt.executeUpdate();
		if(result>0){
			rs = pstmt.getGeneratedKeys();
			if(rs.next())
			id = rs.getInt(1);
		}
	} catch (Exception e) {
		e.printStackTrace();
	}finally{
		DBUtil.close(rs, pstmt, conn);
	}
	return id;
	}
	/**
	 * 实现接口,用来统一实现对数据要各种要求进行查询
	 * 返回List<Order>集合,用户根据需要在定义具体的方法
	 */
	public List<Order> select(String sql, Object[] parameter) throws Exception {
			List<Order> orderList = new ArrayList<Order>();
			Connection conn = null;
			PreparedStatement pstmt = null;
			ResultSet rs = null;
		try {
			conn = DBUtil.getConnection();
			pstmt = conn.prepareStatement(sql);
			if(parameter != null && parameter.length>0){
				for (int i = 1; i <= parameter.length; i++) {
					pstmt.setObject(i, parameter[i-1]);
				}
			}
			rs = pstmt.executeQuery();
			while(rs.next()){
			    Order order= new Order();
			    order.setId(rs.getInt("id"));
			    order.setUserId(rs.getInt("user_id"));
			    order.setStatus(rs.getInt("status"));
			    order.setOrderTime(rs.getInt("order_time"));
			    order.setTotalPrice(rs.getInt("total_price"));
			    order.setReceiveName(rs.getString("receive_name"));
			    order.setFullAddress(rs.getString("email_verify_code"));
			    order.setPostalCode(rs.getString("postal_code"));
			    order.setMobile(rs.getString("mobile"));
			    orderList.add(order);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			DBUtil.close(rs, pstmt, conn);
		}
		return orderList;
	}
	/**
	 * 添加订单
	 */
	public int addOrder(Order order)throws Exception{
		System.out.println("``````````````````````````````");
		return update(ConfigUtil.getValue("ADD_ORDER"),new Object[]{order.getUserId(),order.getStatus(),order.getOrderTime(),order.getTotalPrice()});
	}
	/**
	 * 根据用户Id查询订单信息
	 */
	public Order findById(int id)throws Exception{
		return select(ConfigUtil.getValue("FIND_ORDER_BY_ID"),new Object[]{id}).get(0);
	}
	public static void main(String[] args) throws Exception {
		System.out.println(new OrderDaoImpl().findById(3));
	}
}
